package digital.store.springmvc.dao.impl;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import digital.store.springmvc.dao.CustomerDao;
import digital.store.tutorial.springmvc.model.Customer;

@Repository
public class CustomerDaoImpl implements CustomerDao {
	@PersistenceContext
	private EntityManager em;
	  
	public void saveOrUpdate(Customer customer) {
		if (customer.getId() != null) {
	            em.merge(customer);
	        } else {
	            em.persist(customer);
	        }
	    }
	    
	public void delete(Long id) {
		Customer customer = findById(id);
	    em.remove(customer);
	    }
	    
	@SuppressWarnings("unchecked")
	public List<Customer> findAll() {
	    return em.createQuery("SELECT c FROM Customer c").getResultList();
	    }
	    
    public Customer findById(Long id) {
        return em.find(Customer.class, id);
    }
    
}
